package com.trip.api;

import java.io.*;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.trip.config.AppUser;
import com.trip.config.CommonProperties;
import com.trip.dao.tables.State;
import com.trip.dao.tables.pojos.PicDomain;
import com.trip.dao.tables.pojos.StateDomain;
import com.trip.dao.tables.pojos.TagDomain;
import com.trip.service.BasicInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Api("Basic Info API")
@RequestMapping("/res/")
@RestController
public class BasicInfoController {

	@Autowired
	private CommonProperties commonProperties;

	@Autowired
	private BasicInfoService basicInfoService;

	@ApiOperation(value = "Get picture by ID")
	@RequestMapping(value="pic/{picId}",method = RequestMethod.GET)
	public void getPicStream(HttpServletRequest request, HttpServletResponse response,@PathVariable  String picId) {

		PicDomain picDomain=basicInfoService.queryPicById(picId);
		if(picDomain==null||picDomain.getFileName()==null){
			response.setStatus(404);
			return;
		}

		File file = new File(commonProperties.getPicConfig().getPicFolder()+"/"+picDomain.getFileName());
		if(picDomain.getType()==1) {
			file = new File(commonProperties.getPicConfig().getPicFolder()+"/pae/"+picDomain.getFileName());
		}if(picDomain.getType()==2){
			file = new File(commonProperties.getPicConfig().getPicFolder()+"/user/"+picDomain.getFileName());
		}else if(picDomain.getType()==3){
			file = new File(commonProperties.getPicConfig().getPicFolder()+"/plan/"+picDomain.getFileName());
		}


		if ((!file.exists()) || (!file.isFile())) {
			response.setStatus(404);
			return;
		}

		byte[] buf = new byte[4096];
		ServletOutputStream sos = null;
		InputStream is = null;
		try {
			sos = response.getOutputStream();
			is = new FileInputStream(file);
			int l;
			while (((l = is.read(buf)) != -1)) {
				sos.write(buf, 0, l);
			}
		} catch (IOException e) {
			response.setStatus(404);

		}finally {
			try {
				is.close();
				sos.flush();
				sos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }

    @ApiOperation(value = "Get all state")
    @RequestMapping(value = "state",method = RequestMethod.GET)
    public ControllerResult<List<StateDomain>> queryStateList(){
		return ControllerResult.success(basicInfoService.queryStateList());
	}

	@ApiOperation(value = "Get tag by type",notes = "Type value(1:Place;2:Experience)")
	@RequestMapping(value = "tag",method = RequestMethod.GET)
	public ControllerResult<List<TagDomain>> queryTagList(@ApiParam(allowableValues ="1,2") Integer type){
    	return ControllerResult.success(basicInfoService.queryTagList(type));
	}
}
